<template>
	<div class="tables">
		<div class="mb-4">
			<el-button :icon="Plus" type="primary" plain @click="addData">新增</el-button>
			<el-popconfirm title="确定删除所选内容吗？" @confirm="deleteElement">
				<template #reference>
					<el-button :icon="Delete" type="danger" plain>批量删除</el-button>
				</template>
			</el-popconfirm>
		</div>
		<el-table v-loading="loading" ref="multipleTableRef" :data="tableData" style="width: 100%;margin-top: 20px;"
			@selection-change="handleSelectionChange">
			<el-table-column type="selection" :selectable="selectable" width="55" />
			<el-table-column v-for="column in pageData.columns" :key="column.prop" :prop="column.prop"
				:label="column.label" :min-width="column.minWidth">
				<template v-if="column.prop=='classicon'" #default="scope">
					<img style="height: 30px;" :src="classiconurl(scope.row.classicon)" alt="" />
				</template>
				<template v-if="column.prop=='enable'" #default="scope">
					<el-switch 
						v-model="scope.row.enable" 
						:active-value="1" 
						:inactive-value="0"
						@change="enableColumn(scope.row)" />
				</template>
			</el-table-column>
			<el-table-column label="操作" class="notranslate">
				<template #default="scope">
					<el-dropdown>
						<el-button>操作</el-button>
						<template #dropdown>
							<el-dropdown-menu>
								<el-dropdown-item @click="editeRowData(scope.row)">
									<icon name="bianji" />修改
								</el-dropdown-item>
								<el-dropdown-item @click="deleteRowData(scope.row)">
									<icon name="shanchu" />删除
								</el-dropdown-item>
							</el-dropdown-menu>
						</template>
					</el-dropdown>
				</template>
			</el-table-column>
		</el-table>
		<div class="pagination">
			<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20]"
				:size="size" :disabled="disabled" :background="background"
				layout="total, sizes, prev, pager, next, jumper" :total="totals" locale="zh_CN"
				@size-change="handleSizeChange" @current-change="handleCurrentChange" />
		</div>
		<div class="wxdialog">
			<el-dialog @close="closedialog" v-model="dialogVisible" :title="Tips?'新增':'修改'" width="600" draggable>
				<div>
					<el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules"
						label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>
						<el-form-item label="分类名称" prop="name">
							<el-input v-model="ruleForm.name" placeholder="请填写分类名称" />
						</el-form-item>
						<el-form-item label="分类图标">
							<el-upload class="avatar-uploader" :action="uploadHost" :show-file-list="false"
								:on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
								<img v-if="imageUrl" :src="imageUrl" class="avatar" />
								<el-icon v-else class="avatar-uploader-icon">
									<Plus />
								</el-icon>
							</el-upload>
						</el-form-item>
						<el-form-item label="是否启用" prop="url">
							<el-switch 
							:active-value="1" 
							:inactive-value="0" 
							v-model="ruleForm.enable" />
						</el-form-item>
					</el-form>
				</div>
				<template #footer>
					<div class="dialog-footer">
						<el-button @click="resetForm(ruleFormRef)">取消</el-button>
						<el-button type="primary" @click="submitForm(ruleFormRef)">
							确定
						</el-button>
					</div>
				</template>
			</el-dialog>
		</div>
	</div>
</template>

<script lang="ts" setup>
	import { ref, reactive, onMounted, getCurrentInstance, computed } from 'vue'
	import type { TableInstance, ComponentSize, FormInstance, FormRules } from 'element-plus'
	import { Search, Refresh, Plus, EditPen, Delete, Download } from '@element-plus/icons-vue'
	import type { UploadProps } from 'element-plus'

	const currentPage = ref(1)
	const pageSize = ref(10)
	const size = ref<ComponentSize>('default')
	const background = ref(true)
	const disabled = ref(false)
	let totals = ref<number>(0)
	let dialogVisible = ref(false)
	const loading = ref(true)
	const Tips = ref(true)
	const { proxy } = getCurrentInstance()!;
	const uploadHost = proxy.Uploadhost;
	let currentrow = reactive({})
	const pageData = reactive({
		columns: [
			{
				prop: 'name',
				label: '分类名称',
				minWidth: '100px'
			},
			{
				prop: 'classicon',
				label: '分类图标',
				minWidth: '100px'
			},
			{
				prop: 'enable',
				label: '启用状态',
				minWidth: '100px'
			}
		]
	});

	const closedialog = () => {
		ruleForm.enable=0;
		ruleForm.name = ""
		imageUrl.value = ""
		ruleForm.classicon = ""
	}

	const imageUrl = ref('')

	const handleAvatarSuccess : UploadProps['onSuccess'] = (
		response,
		uploadFile
	) => {
		imageUrl.value = URL.createObjectURL(uploadFile.raw!)
		ruleForm.classicon = response.data[0]
	}

	const beforeAvatarUpload : UploadProps['beforeUpload'] = (rawFile) => {
		return true
	}

	interface User {
		id : number
		name : string,
		classicon : string
	}

	let tableData : User[] = ref([])
	onMounted(() => {
		getclassifys()
	})
	// 动态计算出image的地址
	const classiconurl = computed(() => {
		return (item) => proxy.imgHost + `${item}`;
	});

	const getclassifys = () => {
		proxy.$http.post('/getclassifys', { "currentPage": currentPage.value, "pageSize": pageSize.value }).then((res) => {
			console.log(res)
			tableData.value = res.data;
			totals.value = res.totals;
		}).catch((error) => {
			console.log(error)
		})
	}

	setTimeout(() => {
		loading.value = false
	}, 2000)
	interface RuleForm {
		name : string,
		classicon : string,
		isenable : number
	}

	const formSize = ref<ComponentSize>('default')
	const ruleFormRef = ref<FormInstance>()
	let ruleForm = reactive<RuleForm>({
		name: '',
		classicon: '',
		enable: 0
	})

	const rules = reactive<FormRules<RuleForm>>({
		name: [
			{ required: true, message: '请填写名称', trigger: 'blur' },
			{ min: 1, max: 30, message: '请输入正确的名称', trigger: 'blur' },
		]
	})

	const submitForm = async (formEl : FormInstance | undefined) => {
		if (!formEl) return
		await formEl.validate((valid, fields) => {
			if (valid) {
				if (Tips.value) { //新增
					proxy.$http.post('/pushdata', ruleForm).then((res) => {
						getclassifys()
						dialogVisible.value = false

					}).catch((error) => {
						console.log(error)
					})
				} else {
					const { id } = currentrow;
					const { name, classicon, enable } = ruleForm;
					console.log(classicon)
					proxy.$http.post('/updateclass', { id: id, name: name, classicon: classicon, enable: enable }).then((res) => {
						getclassifys()
						dialogVisible.value = false

					}).catch((error) => {
						console.log(error)
					})
				}

			} else {

				console.log('error submit!', fields)
				return false
			}
		})

	}

	const resetForm = (formEl : FormInstance | undefined) => {
		if (!formEl) return
		formEl.resetFields()
		dialogVisible.value = false
	}

	const options = Array.from({ length: 10000 }).map((_, idx) => ({
		value: `${idx + 1}`,
		label: `${idx + 1}`,
	}))

	const handleSizeChange = (val : number) => {
		console.log(`${val} items per page`)
	}
	const handleCurrentChange = (val : number) => {
		console.log(`current page: ${val}`)
		proxy.$http.post('/getclassifys', { "currentPage": val, "pageSize": pageSize.value }).then((res) => {
			console.log(res)
			tableData.value = res.data;
			totals.value = res.totals;
		}).catch((error) => {
			console.log(error)
		})
	}

	const addData = () => {
		Tips.value = true
		dialogVisible.value = true
	}

	const editeRowData = (row) => {
		Tips.value = false
		dialogVisible.value = true
		ruleForm.name = row.name
		ruleForm.classicon = row.classicon
		ruleForm.enable=row.enable
		if (row.classicon) imageUrl.value = proxy.imgHost + row.classicon
		else imageUrl.value = ''
		currentrow = row;
	}

	const deleteRowData = (row) => {
		proxy.$http.post('/deleteclass', { "id": row.id }).then((res) => {
			getclassifys()
		}).catch((error) => {
			console.log(error)
		})
	}

	const editData = () => {
		Tips.value = false
		dialogVisible.value = true
	}

	const formInline = reactive({
		name: '',
	})

	const onSubmit = () => {
		console.log('submit!')
	}

	const onreset = () => {
		formInline.name = "";
	}

	const multipleTableRef = ref<TableInstance>()
	const multipleSelection = ref<User[]>([])

	const selectable = (row : User) => ![].includes(row.id)
	const toggleSelection = (rows ?: User[], ignoreSelectable ?: boolean) => {
		if (rows) {
			rows.forEach((row) => {
				multipleTableRef.value!.toggleRowSelection(
					row,
					undefined,
					ignoreSelectable
				)
			})
		} else {
			multipleTableRef.value!.clearSelection()
		}
	}
	const handleSelectionChange = (val : User[]) => {
		multipleSelection.value = val
	}
	const enableColumn = (row)=>{
		console.log(row)
		proxy.$http.post('/updateclass',row).then((res)=>{
			console.log(res)
		}).catch(()=>{
			
		})
	}
	const deleteElement = () => {
		const newobj = multipleSelection.value.map((item) => {
			return item.id
		})
		proxy.$http.post('/deleteclass', { "id": newobj }).then((res) => {
			getclassifys()
		}).catch((error) => {
			console.log(error)
		})
	}
</script>
<style scoped>
	.tables {
		/* width: 98%; */
		margin: 20px auto;
		padding: 20px;
		box-sizing: border-box;
		background: #fff;
	}

	.demo-form-inline .el-input {
		--el-input-width: 220px;
	}

	.demo-form-inline .el-select {
		--el-select-width: 220px;
	}

	/deep/ .el-table th.el-table__cell {
		background-color: #f8f8f8;
	}

	/deep/ .el-dropdown {
		color: #409eff;
		cursor: pointer;
	}

	/deep/ .el-table .cell {
		line-height: unset;
		/* cursor: pointer; */
	}

	/deep/ .el-popup-parent--hidden {
		width: 100% !important;
	}

	.demo-pagination-block+.demo-pagination-block {
		margin-top: 10px;
	}

	.demo-pagination-block .demonstration {
		margin-bottom: 16px;
	}

	.pagination {
		margin: 20px auto;
		display: flex;
		justify-content: flex-end;
	}

	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
		border: 1px dashed;
	}
</style>